package config

import (
	"os"
	"bufio"
	"io"
	"strings"
	"strconv"
)

var (
	ConfigMap map[string]string
)

func Init(fileName string)  {
	ConfigMap = make(map[string]string)

	f,err := os.Open(fileName)
	if err != nil {
		panic("open file is error")
	}
	defer f.Close()

	rd := bufio.NewReader(f)
	for {
		d,_,err := rd.ReadLine()
		if err != nil {
			if err == io.EOF {
				break
			}
			panic("file read is error")
		}
		s := strings.TrimSpace(string(d))
		if strings.Index(s, "#") == 0 {
			continue
		}

		index := strings.Index(s, "=")
		if index <= 0 {
			 continue
		}

		key := strings.TrimSpace(s[:index])
		if len(key) <= 0 {
			continue
		}
		val := strings.TrimSpace(s[index+1:])
		ConfigMap[key] = val
	}
}

func GetString(key string) string {
	return ConfigMap[key]
}

func GetStringDef(key string, def string) string {
	val,ok := ConfigMap[key]
	if !ok {
		return def
	}
	return val
}

func GetInt64Def(key string, def int64) int64 {
	val,err := strconv.Atoi(ConfigMap[key])
	if err != nil {
		return def
	}
	return int64(val)
}
